package com.web;



import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class BaseServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) {

        //获取请求路径
        String uri = req.getRequestURI();

        //获取请求路径的最后一段，即方法名
        int index = uri.lastIndexOf('/');
        String methodName = uri.substring(index + 1);

        //获取当前Servlet对象
        Class<? extends BaseServlet> currentClass = this.getClass();
        //获取当前Servlet的Method对象
        try{
            Method method = currentClass.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(this,req,resp);
        } catch (InvocationTargetException | NoSuchMethodException | IllegalAccessException e) {
            e.printStackTrace();
        }
    }
}
